import requests
from utils.base_response import BaseResponse


class HttpRequest:
    def __init__(self, method, url, data=None, headers=None):
        self.method = method.lower()
        self.url = url
        self.data = data
        self.files = None
        self.headers = headers
        # 请求结果，自己进行了简单封装
        self.res = BaseResponse()
        # 请求结果，未进行封装
        self.response_data = {
            'response_code': '',
            'response_encoding': '',
            'response_apparent_encoding': '',
            'response_headers': '',
            'response_body': '',
        }

    # 获取文件字段
    def get_files(self):
        files = []
        if isinstance(self.data,dict):
            old_files = self.data.get('files')
            if old_files:
                for key in old_files:
                    for my_path in old_files[key]:
                        dt = (key, open(my_path,'rb'))
                        files.append(dt)
                self.files = files

    def get_request_data(self):
        # 数据处理
        self.get_files()
        request_data = {'headers': self.headers, 'verify': False, 'files': self.files}
        if self.method == 'get':
            request_data['params'] = self.data
        else:
            content_type = self.headers.get('Content-Type') if self.headers else None
            if self.files:
                my_data = {key:self.data[key] for key in self.data if key != 'files'}
            else:
                my_data = self.data
            if isinstance(content_type, str) and content_type.find('application/json') != -1:
                request_data['json'] = my_data
            else:
                request_data['data'] = my_data
        return request_data

    def http_request(self):
        request_data = self.get_request_data()
        print("self.url:", self.url)
        print("request_data:",request_data)
        try:
            response = requests.request(self.method, self.url, **request_data)
        except Exception as e:
            self.res.status = 1
            self.res.error = str(e.args)
            self.res.msg = '请求失败'
            # raise e
        else:
            self.response_data['response_code'] = response.status_code  # 状态码
            self.response_data['response_encoding'] = response.encoding  # 从HTTP header中获取的响应内容编码方式
            self.response_data['response_apparent_encoding'] = response.apparent_encoding  # 从内容分析出的响应内容的编码方式（备选编码方式）
            self.response_data['response_headers'] = dict(response.headers)  # http响应内容的头部内容
            try:
                self.response_data['response_body'] = response.json()
                self.res.status = 0
                self.res.msg = '请求成功'
            except Exception as e:
                self.response_data['response_body'] = response.text
                self.res.status = 1
                self.res.error = str(e.args)
                self.res.msg = '非json数据'


if __name__ == '__main__':
    method = 'POST'
    url = "http://127.0.0.1:8113/account/register"
    data = {"username": "jiangtao92512", "pwd": "jiangtao925"}
    headers = {
        # "Content-Type": "multipart/form-data",
        "ACCOUNTTOKEN": "fb3eeae7-3087-4c1e-a898-ae678060448b"
    }
    files = [
        ('sql_data_str', open(r"D:\python3\jiangsqobj\media\Attachment\file_data\timg_4.jpg", 'rb'))
    ]
    # obj = HttpRequest(method, url, data, headers)
    # obj.http_request()
    # print(obj.res.dict)
    # print(obj.response_data)
    # print(obj.response_data.get('response_body'))

    response = requests.request("POST", url, headers=headers, data=data, files=files)

    print(response.text)

